package com.bkhc.product.service;

import com.bkhc.common.permissions.bean.RoleDetail;
import com.bkhc.common.permissions.bean.UserPermission;
import com.bkhc.common.service.UserService;
import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.response.PageUtil;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.OrderItemVo;
import com.bkhc.common.vo.OrderVo;

import com.bkhc.common.vo.UserBean;
import com.bkhc.product.entity.Brand;
import com.bkhc.product.entity.BrandGoodPrice;
import com.bkhc.product.entity.GoodsSpec;
import com.bkhc.product.entity.Product;
import com.bkhc.product.repository.BrandRepository;
import com.bkhc.product.repository.GoodspecRepository;
import com.bkhc.product.repository.OrderRepository;

import com.bkhc.product.repository.ProductRepository;
import com.bkhc.product.vo.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderService {

    @Autowired
    private OrderRepository repository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private GoodspecRepository goodspecRepository;

    @Autowired
    private BrandService brandService;

    @Autowired
    private UserService userService;

    public ResultJson<?> getOrders(OrderVo order, int pageNum, int pageSize) {
        UserBean crruentUser = CommonUtil.getCrruentUser();
        UserPermission userPermission = userService.queryUserPermission(crruentUser.getUserId());
        boolean isAdmin = userPermission.getRoles().stream().anyMatch(roleDetail -> "admin".equals(roleDetail.getRole_code()));
        List<Product> products = null;
        if(!isAdmin){
//            order.setOrderStatus("2");
            products = productRepository.findAllByPartnerId(crruentUser.getUserId());
        }
        PageUtil res = null;
        if(!CollectionUtils.isEmpty(products)){
            List<String> productCodes = products.stream().map(Product::getProductCode).collect(Collectors.toList());
            res= repository.getProductorOrders(order,productCodes, pageNum, pageSize);
        }
        res = repository.getProductorOrders(order,null, pageNum, pageSize);
        if(!CollectionUtils.isEmpty(res.getList())){
         List<Map<String,Object>> orders= (List<Map<String,Object>>) res.getList();
         List<String> allgoodsCode = new ArrayList<>();
         for(Map<String,Object> map:orders){
             List<Map<String,Object>> orderitems= (List<Map<String,Object>>)map.get("orderitems");
             for(Map<String,Object> orderitem:orderitems){
                 allgoodsCode.add(orderitem.get("goodsCode")+"");
             }
         }
            List<GoodsSpec> allspes = goodspecRepository.findByGoodsCodeIn(allgoodsCode);
            for(Map<String,Object> map:orders){
                List<Map<String,Object>> orderitems= (List<Map<String,Object>>)map.get("orderitems");
                for(Map<String,Object> orderitem:orderitems){
                    orderitem.put("goodsSpecList",allspes.stream().filter(x->x.getGoodsCode().equals(orderitem.get("goodsCode")+"")));
                }
            }
}
        ResultJson<PageUtil> resultJson = ResultJson.success();
        resultJson.setData(res);
        return resultJson;
    }

    public List<OrderItemVo> queryOrderItem(String orderCode) {
        List<OrderItemVo> res = repository.queryOrderItem(orderCode);
        return res;
    }

    public List<OrderItem> buildOrder(List<OrderItem> orderItems) {
     if (!CollectionUtils.isEmpty(orderItems)){
         Product product = productRepository.findByProductCode(orderItems.get(0).getProductCode());
         Brand brand = brandRepository.findByBrandCode(orderItems.get(0).getBrandCode());
         for(OrderItem item:orderItems){
             item.setBrandName(brand.getBrandName());
             item.setProductName(product.getProductName());
             BigDecimal money = item.getPrice().multiply(new BigDecimal(item.getNum()));
             item.setCount(money);
         }
         return  orderItems;
     }
     return null;
    }

    public ResultJson<?> complateOrder(String orderCode) {
        return updateOrderStatusByProductor(orderCode,1111+"");
    }

    public ResultJson<?> cancelOrder(String orderCode) {
        return updateOrderStatusByProductor(orderCode,1110+"");
    }

    public ResultJson<?>  updateOrderStatusByProductor(String orderCode,String orderStatus){

        OrderVo order = new OrderVo();
        order.setOrderCode(orderCode);
        order.setOrderAuditStatus(Integer.parseInt(orderStatus));
        UserBean crruentUser = CommonUtil.getCrruentUser();
        String userId=crruentUser.getUserId();
       // UserPermission userPermission = userService.queryUserPermission(crruentUser.getUserId());
     //   boolean isAdmin = userPermission.getRoles().stream().anyMatch(roleDetail -> "admin".equals(roleDetail.getRole_code()));
//        if(!isAdmin){
//            List<Product> products = productRepository.findAllByPartnerId(userId);
//            if(!CollectionUtils.isEmpty(products)){
//                List<String> productCodes = products.stream().map(Product::getProductCode).collect(Collectors.toList());
//                PageUtil res = repository.getProductorOrders(order,productCodes, 1, 1);
//                List<Object> orders = (List<Object>)res.getList();
//                if(!CollectionUtils.isEmpty(orders)){
//                    repository.assginToPartner(orderCode);
//                    ResultJson<PageUtil> resultJson = ResultJson.success();
//                    return resultJson;
//                }else{
//                    ResultJson<PageUtil> resultJson = ResultJson.failure(ResultCode.NO_ORDER_DATA);
//                    return resultJson;
//                }
//            }
//        }else{
            repository.assginToPartner(orderCode);
            ResultJson<PageUtil> resultJson = ResultJson.success();
            return resultJson;
       // }

//        ResultJson<PageUtil> resultJson = ResultJson.failure(ResultCode.FORBIDDEN);
//        return resultJson;
    }

    public ResultJson<?> queryOrderByUserId(OrderVo orderVo, int pageIndex, int pageSize) {
        UserBean user = CommonUtil.getCrruentUser();
        if(user == null){
            return ResultJson.failure(ResultCode.NO_LOGIN);
        }
        if(orderVo ==null){
            orderVo = new OrderVo();
        }
        orderVo.setUserId(user.getUserId());
        PageUtil res = repository.getOrdersByUserId(orderVo, pageIndex, pageSize);
        if(!CollectionUtils.isEmpty(res.getList())){
            List<Map<String,Object>> orders= (List<Map<String,Object>>) res.getList();
            List<String> allgoodsCode = new ArrayList<>();
            for(Map<String,Object> map:orders){
                List<Map<String,Object>> orderitems= (List<Map<String,Object>>)map.get("orderitems");
                for(Map<String,Object> orderitem:orderitems){
                    allgoodsCode.add(orderitem.get("goodsCode")+"");
                }
            }
            List<GoodsSpec> allspes = goodspecRepository.findByGoodsCodeIn(allgoodsCode);
            for(Map<String,Object> map:orders){
                List<Map<String,Object>> orderitems= (List<Map<String,Object>>)map.get("orderitems");
                for(Map<String,Object> orderitem:orderitems){
                    orderitem.put("goodsSpecList",allspes.stream().filter(x->x.getGoodsCode().equals(orderitem.get("goodsCode")+"")));
                }
            }
        }

        ResultJson<PageUtil> resultJson = ResultJson.success();
        resultJson.setData(res);
        return resultJson;
    }
}
